package com.pactera.madp.cp.service.impl;

import com.pactera.madp.cp.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 全局缓存
 * @author
 * @date 2021-04-27 21:09
 *
 */
@Service("cacheService")
public class CacheServiceImpl implements CacheService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public void saveAuthorizerToken(String key, String token) {
        // 登录令牌过期时间为2小时
        redisTemplate.opsForValue().set(key, token,2, TimeUnit.HOURS);
    }

    @Override
    public void saveRefreshToken(String key, String token) {
        redisTemplate.opsForValue().set(key, token);
    }

    @Override
    public void saveComponentToken(String key, String token) {
        // 登录令牌过期时间为2小时
        redisTemplate.opsForValue().set(key, token,7200, TimeUnit.SECONDS);
    }

    @Override
    public void saveToken(String key, String token) {
        redisTemplate.opsForValue().set(key, token);
        // 登录令牌过期时间为2小时
        redisTemplate.expire(key, 2, TimeUnit.HOURS);
    }

    @Override
    public void saveTempToken(String key, String token) {
        redisTemplate.opsForValue().set(key, token);
        // 临时令牌过期时间为1小时
        redisTemplate.expire(key, 1, TimeUnit.HOURS);
    }

    @Override
    public void saveTempVaCode(String key, String code) {
        redisTemplate.opsForValue().set(key, code);
        // 临时令牌过期时间为30分钟
        redisTemplate.expire(key, 30, TimeUnit.MINUTES);
    }

    @Override
    public String selectCache(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    @Override
    public void saveTicket(String ticket) {
        redisTemplate.opsForValue().set("encrypt", ticket);
        // 临时令牌过期时间为1小时
        redisTemplate.expire("encrypt", 1, TimeUnit.HOURS);
    }

    @Override
    public void deleteCache(String userId) {
        redisTemplate.delete(userId);
    }

    @Override
    public void saveVideoNumCode(String key, int vaCode) {
        String num = String.valueOf(vaCode);
        redisTemplate.opsForValue().set(key, num);
    }

    @Override
    public int selectVideoNum(String videoNum) {
        return Integer.parseInt(redisTemplate.opsForValue().get(videoNum));
    }

}
